<style lang="less">
  .container-inner {
    display: flex;
    flex-direction: row-reverse;
  }

  .container-k {
    flex-grow: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 0rpx 0;
    box-sizing: border-box;
  }

  .searchLetter {
    flex-shrink: 0;
    width: 80rpx;
    text-align: center;
    display: flex;
    flex-direction: column;
    color: #666;
  }

  .searchLetter div {
    margin-top: 20rpx;
  }

  .touchClass {
    /* background-color: #fff; */
    color: #fff;
    padding-top: 16rpx;
    padding-bottom: 16rpx;
    position: absolute;
    z-index: 99;
  }

  .showSlectedLetter {
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 50%;
    left: 50%;
    margin: -100rpx;
    width: 200rpx;
    height: 200rpx;
    border-radius: 20rpx;
    font-size: 52rpx;
    z-index: 1;
  }

  .selection {
    display: flex;
    width: 100%;
    flex-direction: column;
    margin-top: 0rpx;
  }

  .selectCity {
    padding: 0px 3rpx;
    background-color: #fff;
  }

  .item_letter {
    display: flex;
    background-color: #f5f5f5;
    height: 52rpx;
    padding-left: 34rpx;
    align-items: center;
    font-size: 24rpx;
    color: #666;
  }

  .item_city {
    display: flex;
    background-color: #fff;
    height: 100rpx;
    padding-left: 34rpx;
    align-items: center;
    border-bottom: 1rpx solid #ededed;
    font-size: 24rpx;
    color: #666;
  }

  .hotcity-common {
    font-size: 24rpx;
    color: #666;
    padding-bottom: 0;
    padding: 8rpx 0;
    display: inline-block;
    margin: 0px 16px;
  }

  .hotCity {
    padding-right: 50rpx;
    margin: auto;
  }

  .thisCityName {
    display: inline-block;
    border: 1rpx solid #0098ff;
    border-radius: 8rpx;
    padding: 5rpx 8px;
    font-size: 24rpx;
    color: #0098ff;
    text-align: center;
    /* min-width: 132rpx; */
    margin: 16rpx 0;
  }

  .thishotText {
    color: #0098ff;
    font-size: 20rpx;
    margin: 0 !important;
  }

  .slectCity {
    border-color: #0098ff !important;
  }

  .slectCity div {
    color: #0098ff !important;
  }

  .weui-grid {
    padding: 10rpx 0;
    width: 200rpx;
    box-sizing: border-box;
    border: 1rpx solid #ececec;
    border-radius: 8rpx;
    background-color: white;
    margin: 8rpx 0;
  }

  .weui-grids {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    border: 0px;
  }

  .weui-grid__label {
    display: block;
    text-align: center;
    color: #333;
    font-size: 24rpx;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .ul {
    display: block;
    color: grey;
    margin-left: 20rpx;
  }

  .li {
    display: block;
    font-weight: 100;
    font-size: 28rpx;
    padding: 16rpx 0;
  }
  /* input {
  background-color: #eee;
}

.input {
  padding: 16rpx;
  border-bottom: 1rpx solid #f1f1f1;
} */

  .county {
    display: flex;
    flex-wrap: wrap;
  }

  .icon-adress {
    width: 16px;
    height: 16px;
    margin: 0px 3px 0px 0px;
    position: relative;
    top: 1px;
  }
  /*侧滑弹框  */

  .animation {
    z-index: 999;
    float: left;
    /* //动画初始前向右移100vh */
    right: -100vh;
    width: 100%;
    height: 100%;
  }
    .animationT {
    z-index: 1000;
    float: left;
    /* //动画初始前向右移100vh */
    right: -100vh;
    width: 100%;
    height: 100%;
  }
  .animation-content {
    width: 80%;
    height: 100%;
    background: #fff;
    position: absolute;
    right: 0;
    overflow-y:scroll;
  }
  .animat_bg{
    /* background: rgba(0, 0, 0, 0.2); */
    width: 20%;
    height: 100%;
    position: absolute;
    left: 0;
  }
  .animas{
    height:100%;
    position:fixed;
  }
  .animak{
    background: rgba(0, 0, 0, 0.2);
    width: 100%;
    height:100%;
    position:fixed;
    z-index: 100;
  }
  .linked_blue{
  color: #0098FF;
}
</style>
<template>
  <div class="container-inner">
    <div class="animak" wx:if="{{condition}}"></div>
    <div class='animation animas' animation="{{animationData}}" >
      <div class="animat_bg" @tap="closeKs"></div>
      <div class='animation-content' style="background:rgba(255, 255, 255, 0.8);">
        <div class='pricezone'>
          <!-- <div class="item_letter" id="#">#</div> -->
          <div class="item_city" hover-class="linked_blue" data-code="100011" data-city="全省" @tap="bindAlla">
            全省
          </div>
          <div class="item_letter" id="1">#  城市</div>
          <div class="item_city" hover-class="linked_blue" wx:for="{{countyList}}" wx:for-item="item" wx:key="id" data-level="{{item.level}}" data-id="{{item.cityId}}" data-code="{{item.id}}" data-city="{{item.cityName}}"
            @tap="bindCounty">
            {{item.cityName}}
          </div>
        </div>
      </div>
    </div>

    <div class='animationT animas' animation="{{animationDT}}">
      <div class="animat_bg" @tap="closeKe"></div>
      <div class='animation-content'>
        <div class='pricezone'>
          <div class="item_city" hover-class="linked_blue" data-code="100011" data-city="全市" @tap="bindAlla">
            全市
          </div>
          <div class="item_letter" id="1"># 区县</div>
          <div class="item_city" hover-class="linked_blue" wx:for="{{completeList}}" wx:for-item="item" wx:key="id" data-code="{{item.id}}"
            data-city="{{item.name}}" @tap="bindCocity">
            {{item.name}}
          </div>
        </div>
      </div>
    </div>

      <div class="searchLetter touchClass">
        <div class="thishotText" @tap="hotCity">
          <div style="margin-top:{{itemH}}px;color: #0098ff;">#</div>
        </div>
        <div wx:for="{{searchLetter}}" wx:key="{{item.name}}" style="color:#0098ff;font-size:20rpx;" wx:key="{{item.name}}" data-letter="{{item.name}}" catchtouchend="clickLetter">{{item.name}}</div>
      </div>
      <div class="container-k">
        <!-- <block > -->
          <div wx:if="{{isShowLetter}}" class="showSlectedLetter">
            {{toastShowLetter}}
          </div>
        <!-- </block> -->
        <scroll-div scroll-y="true" style="height:{{winHeight}}px" bindscroll="bindScroll" scroll-into-div="{{scrollTopId}}" scroll-top="{{scrollTop}}">

          <div class="selectCity" @tap="bindCounty2" data-city="{{city}}" data-province="{{province}}">
            <div class="hotcity-common">
              <image class="icon-adress" mode="aspectFit" src="../images/icon_address.png"></image>
              定位到当前位置
            </div>
            <div class="thisCityName" data-city="{{city}}" data-code="{{currentCityCode}}">{{dingwei}}</div>

          </div>
          <div class="item_letter" id="#">#</div>
          <div class="item_city" hover-class="linked_blue" data-code="100011" data-city="全国" @tap="bindAlla">
            全国
          </div>
          <div class="selection" wx:for="{{cityList}}" wx:key="{{item.firstLetter}}">

            <div class="item_letter" id="{{item.firstLetter}}">{{item.firstLetter}}</div>
            <div class="item_city" hover-class="linked_blue" wx:for="{{item.provinces}}" wx:for-item="ct" wx:key="provinceId" data-level="{{ct.level}}" data-id="{{ct.provinceId}}" data-code="{{ct.id}}" data-city="{{ct.provinceName}}"
              @tap="bindCity">
              {{ct.provinceName}}
            </div>
          </div>



        </scroll-div>

      </div>
    </div>
</template>

<script>
  import wepy from 'wepy'
  import { connect } from 'wepy-redux'
  import Panel from '@/components/panel' // alias example
  import Toast from 'wepy-com-toast'
  import config from '../utils/config';
  import api from '../api/api';
  import util from '../utils/util';
  @connect({
    num(state) {
      return state.counter.num
    },
    asyncNum(state) {
      return state.counter.asyncNum
    },
    sumNum(state) {
      return state.counter.num + state.counter.asyncNum
    }
  })

  export default class areaSelect extends wepy.page {
    config = {
      navigationBarTitleText: '省市区选择'
    }
    components = {
      toast: Toast
    }

    // mixins = []

    data = {
      searchLetter: [],
      showLetter: "",
      winHeight: 0,
      itemH:0,
      cityList: [],
      isShowLetter: false,
      scrollTop: 0,//置顶高度
      scrollTopId: '',//置顶id
      dingwei: "定位中...",
      currentCityCode: '',
      hotcityList: [{ cityCode: 110000, city: '北京市' }, { cityCode: 310000, city: '上海市' }, { cityCode: 440100, city: '广州市' }, { cityCode: 440300, city: '深圳市' }, { cityCode: 330100, city: '杭州市' }, { cityCode: 320100, city: '南京市' }, { cityCode: 420100, city: '武汉市' }, { cityCode: 120000, city: '天津市' }, { cityCode: 610100, city: '西安市' },],
      commonCityList: [{ cityCode: 110000, city: '北京市' }, { cityCode: 310000, city: '上海市' }],
      countyList: [{ cityCode: 110000, county: 'A区' }, { cityCode: 310000, county: 'B区' }, { cityCode: 440100, county: 'C区' }, { cityCode: 440300, county: 'D区' }, { cityCode: 330100, county: 'E县' }, { cityCode: 320100, county: 'F县' }, { cityCode: 420100, county: 'G县' }],
      cityAreac:"",////区
      inputName: '',
      completeList: [],
      county: '',
      condition: false,
      toastShowLetter: "",
      animationData:"",
      animationDT:"",
      show:false,
      animation:"",
      animationT:"",
      tHeight: 0,
        bHeight: 0,
        startPageY: 0,
      province: '',
      city: ''
    }

    computed = {

    }

    methods = {
      searchStart: function (e) {
        var showLetter = e.currentTarget.dataset.letter;
        var pageY = e.touches[0].pageY;
        this.setScrollTop(showLetter);
        this.nowLetter(pageY);

          this.showLetter=showLetter;
          this.startPageY= pageY;
          this.isShowLetter=true;

      },
      searchMove: function (e) {
        var pageY = e.touches[0].pageY;
        var startPageY = this.startPageY;
        var tHeight = this.tHeight;
        var bHeight = this.bHeight;
        var showLetter = 0;
        console.log(pageY);
        if (startPageY - pageY > 0) { //向上移动
          if (pageY < tHeight) {
            // showLetter=this.mateLetter(pageY,this);
            this.nowLetter(pageY);
          }
        } else {//向下移动
          if (pageY > bHeight) {
            // showLetter=this.mateLetter(pageY,this);
            this.nowLetter(pageY);
          }
        }
      },
      clickLetter:  (e)=> {////点击右侧字母列表定位
        // console.log(e);
        const showLetter = e.currentTarget.dataset.letter;
        this.toastShowLetter = showLetter;
        this.isShowLetter = true;
        this.scrollTopId = showLetter;
        setTimeout(() => {
          this.isShowLetter = false;
          this.$apply();
        }, 500);

      },
      //点击 # 回到顶部
      hotCity: (e)=> {
        this.scrollTop = 0;
        this.$apply();
      },
      bindScroll: function (e) {
        this.scrollTop = e.detail.scrollTop;
        //  console.log(e.detail);
      },
      bindAlla: function (e) {////选择全国 全省 全市
        if(e.currentTarget.dataset.city!="全国"){
          this.$parent.globalData.defaultCounty=this.city;
        }else{
          this.$parent.globalData.defaultCounty = e.currentTarget.dataset.city;
        }
        this.$parent.globalData.defaultCity='';


        if(e.currentTarget.dataset.city == '全国'){
          this.$parent.globalData.defaultCity='全国';
          this.$parent.globalData.defaultCounty='全国';
        }

        if(e.currentTarget.dataset.city == '全省'){
          this.$parent.globalData.defaultCity= this.city;
          this.$parent.globalData.defaultCounty='';
        }

        wx.reLaunch({
          url: '../pages/find/index'
        })

        // wx.navigateBack();
        // wx.switchTab({
        //   url: 'home/index'
        // })
      },
      ////关闭右侧滑动弹框第一层
      closeKs:()=>{
        var animation = wx.createAnimation({//创建动画
          duration: 800,
          timingFunction: 'ease',
          width: 300,
          height: 800,
          top: 0,
          bottom: 0,
          right: 0,
          backgroundColor: '#fff',
          opcity: 0.5
        });
        this.animation = animation;
        animation.translateX(0 + 'vh').step() //动画效果向右滑动100vh
        this.animationData = animation.export();
        this.condition = false;

      },
      //选择省
      async bindCity(e) {
        this.condition = true;
        var animation = wx.createAnimation({//创建动画
            duration: 800,
            timingFunction: 'ease',
            width: 300,
            height: 800,
            top: 0,
            bottom: 0,
            right: 0,
            backgroundColor: '#fff',
            opcity: 0.5
          });
          this.animation = animation;
          animation.translateX(-100 + 'vh').step() //动画效果向左滑动-100vh
          this.animationData = animation.export();
          // this.show = true;
        this.city = e.currentTarget.dataset.city;
        this.currentCityCode = e.currentTarget.dataset.code;
        this.scrollTop = 0;
        // this.completeList = [];
        // this.selectCounty();
        this.$parent.globalData.defaultCity = this.city;
        // this.$parent.globalData.defaultCounty = '';
        // console.log(this.$parent.globalData.defaultCity);

        // let child = await api.getChildInfo(e.currentTarget.dataset.id, e.currentTarget.dataset.level);
        let child = await api.getChildInfo2(e.currentTarget.dataset.id)
        this.countyList = child;
        this.$apply()
      },
      /////选择城市
      async bindCounty (e) {
        // var animation = wx.createAnimation({//创建动画
        //   duration: 800,
        //   timingFunction: 'ease',
        //   width: 300,
        //   height: 800,
        //   top: 0,
        //   bottom: 0,
        //   right: 0,
        //   backgroundColor: '#fff',
        //   opcity: 0.5
        // });
        // this.animationT = animation;
        // animation.translateX(-100 + 'vh').step() //动画效果向左滑动-100vh
        // this.animationDT = animation.export();
        // this.scrollTop = 0;

        this.county = e.currentTarget.dataset.city;
        this.$parent.globalData.defaultCounty = this.county;
        // console.log(this.$parent.globalData.defaultCounty);
        // wx.navigateBack();
        wx.reLaunch({
          url: '../pages/find/index'
        })

        // let child = await api.getChildInfo(e.currentTarget.dataset.id, e.currentTarget.dataset.level);
        // this.completeList = child;
        // this.$apply()

      },

      async bindCounty2 (e) {

        this.province = e.currentTarget.dataset.province;
        this.county = e.currentTarget.dataset.city;
        this.$parent.globalData.defaultCounty = this.county;
        this.$parent.globalData.defaultCity = this.province;
 
        wx.reLaunch({
          url: '../pages/find/index'
        })

        // let child = await api.getChildInfo(e.currentTarget.dataset.id, e.currentTarget.dataset.level);
        // this.completeList = child;
        // this.$apply()

      },

      ////关闭右侧滑动弹框-第二层
        closeKe: () => {
          var animation = wx.createAnimation({//创建动画
            duration: 800,
            timingFunction: 'ease',
            width: 300,
            height: 800,
            top: 0,
            bottom: 0,
            right: 0,
            backgroundColor: '#fff',
            opcity: 0.5
          });
          this.animationT = animation;
          animation.translateX(0 + 'vh').step() //动画效果向右滑动100vh
          this.animationDT = animation.export();
        },
      /////选择区县
        bindCocity: function (e) {
          console.log(e);
          this.county = e.currentTarget.dataset.city;
          this.$parent.globalData.defaultCounty = this.county;
          console.log(this.$parent.globalData.defaultCounty);
          
          // wx.switchTab({
          //   url: 'home/index'
          // })
        },
      ////重新定位
      reGetLocation: function () {
        this.getLocation();

      },
    }

    setScrollTop (showLetter) {
        var scrollTop = 0;
        var cityList = this.cityList;
        var cityCount = 0;
        var initialCount = 0;
        for (var i = 0; i < cityList.length; i++) {
          if (showLetter == cityList[i].initial) {
            scrollTop = initialCount * 30 + cityCount * 41;
            break;
          } else {
            initialCount++;
            cityCount += cityList[i].data.length;
          }
        }

        this.scrollTop = scrollTop;

      }
    nowLetter(pageY) {//当前选中的信息
          var letterData = this.searchLetter;
          var bHeight = 0;
          var tHeight = 0;
          var showLetter = "";
          for (var i = 0; i < letterData.length; i++) {
            if (letterData[i].tHeight <= pageY && pageY <= letterData[i].bHeight) {
              bHeight = letterData[i].bHeight;
              tHeight = letterData[i].tHeight;
              showLetter = letterData[i].name;
              break;
            }
          }

          this.setScrollTop(showLetter);

          this.bHeight = bHeight;
          this.tHeight = tHeight;
          this.showLetter = showLetter;
          this.startPageY = pageY;
    }

    getLocation() {
      console.log("正在定位城市...");
      this.county = '';
      wx.getLocation({
        type: 'wgs84',
        success: (res) => {
          console.log(res)
          let latitude = res.latitude
          let longitude = res.longitude
          wx.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${config.key}`,
            success: res => {
              console.log('ttt')
              console.log(res.data.result.ad_info.city + res.data.result.ad_info.adcode);
              this.province = res.data.result.ad_info.province;
              this.city = res.data.result.ad_info.city;
              this.dingwei = res.data.result.ad_info.city;
              this.currentCityCode = res.data.result.ad_info.adcode;
              this.county = res.data.result.ad_info.district;
              this.$apply();
              wx.hideLoading()
              // this.selectCounty();
            }
          })
        }
      })
    }

    // 城市json首字母排序
    pySegSort(arr, empty) {
      if(!String.prototype.localeCompare)
          return null;
      var letters = "#ABCDEFGHJKLMNOPQRSTWXYZ".split('');
      var zh = "阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀".split('');
      var segs = [];// 存放数据
      var py = [];// 存放首字母
      var res = {};
      var curr;
      for(let i=0;i<letters.length;i++){
        curr = {
              letter: letters[i],
              data: []
          };
          for(let k=0;k<arr.length;k++){
            if((!zh[i - 1] || zh[i - 1].localeCompare(arr[k].name, 'zh') <= 0) && arr[k].name.localeCompare(zh[i], 'zh') == -1) {
                  curr.data.push(arr[k]);
              }
          }

          if(empty || curr.data.length) {
              py.push(letters[i]);
              segs.push(curr);
              curr.data.sort(function(a, b) {
                  return a.name.localeCompare(b.name, 'zh');
              });
          }
      }

      res["segs"] = segs;
      res["py"] = py;
      return res;
  }

    events = {

    }
    onShow() {

    }
    async onLoad() {

      let province = await api.province2();

      // console.log(this.pySegSort(province))

      // 生命周期函数--监听页面加载
      const cityList = province;
      const sysInfo = wx.getSystemInfoSync();
      console.log(cityList);
      this.winHeight = sysInfo.windowHeight;
      const itemH = this.winHeight - cityList.length * 32;
      let tempArr = [];

      // console.log(cityList)

      cityList.map(
        (item, index) => {
          // console.log(item);
          // console.log(index);
          let temp = {};
          temp.name = item.firstLetter;
          tempArr.push(temp);
        }
      );
      this.searchLetter = tempArr;
      this.cityList = cityList;
      if(cityList.length==26){
        this.itemH=0;
      }else{
        this.itemH = itemH / 2 + 20;
      }

      // console.log(this.itemH);
      this.getLocation();
    }
  }

</script>
